import { GoodsEditComponent } from '../../routes/goods/goods-list/goods-edit/goods-edit.component';
import { ActivatedRouteSnapshot, CanDeactivate, Router, RouterStateSnapshot } from '@angular/router';
import { ComponentFactoryResolver, Injectable } from '@angular/core';
import { MyModalHelper } from '@core/my-modal.helper';
import { LeaveConfirmComponent } from '@shared/leave-confirm/leave-confirm.component';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<GoodsEditComponent> {
  constructor(private modalHelper: MyModalHelper,
              private componentFactoryResolver: ComponentFactoryResolver,
              private router: Router) {
  }

  canDeactivate(
    component: GoodsEditComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Promise<boolean> | boolean {

    let isDirty = false;
    if (component.step2) {
      isDirty = component.step2.validateForm.dirty;
    } else if (component.step1) {
      isDirty = component.step1.componentDirty;
    } else if (component.step0) {
      isDirty = component.step0.validateForm.dirty || component.step0.componentDirty;
    }else {
      isDirty = false;
    }
    if (!isDirty) {
      //未做修改 直接离开
      return true;
    }
    return new Promise((resolve, reject) => {
      this.modalHelper.open(LeaveConfirmComponent, { tipText: '离开本页面将不会保存您编辑修改的信息，确认离开吗？' }, 500, {
        nzTitle: '提示',
      }).subscribe(result => {
        console.log(result);
        if (result) {//离开
          return resolve(true);
        } else {//继续编辑
          return resolve(false);
        }
      }, (error) => {
        console.error('弹窗回调出错：', error);
        return resolve(false);
      });
    });

  }
}
